<template>
  <div class="home">
    <el-container class="content-container" v-if="HighSection">
      <!-- Left column (vertical stack) - 2/5 width -->
      <el-aside class="vertical-stack" style="width: 30%">
        <!-- Temperature Chart -->
        <temperature-chart
            :base-categories="baseTempCategories"
            :current-data="currentTempData"
            class="chart-wrapper"
        />

        <!-- Airflow Chart -->
        <airflow-chart
            :base-categories="baseAirCategories"
            :current-data="currentAirData"
            class="chart-wrapper"
        />
      </el-aside>

      <!-- Right column (horizontal stack) - 3/5 width -->
      <el-main class="horizontal-stack" style="width: 70%">
        <!-- Grid Chart -->
        <all-categories
            :base-categories="baseAirCategories"
            :current-data="currentAirData"
            class="chart-wrapper"
        />

        <all-categories-temp
            :base-categories="baseTempCategories"
            :current-data="currentTempData"
            class="chart-wrapper"
        />
      </el-main>
    </el-container>

    <div class="footPart" v-else>
      <!-- Optional: Show a message or spinner while loading initial data -->
      <p style="text-align: center; padding: 20px;">加载图表中...</p>
    </div>
  </div>
</template>

<script>
// Import child components
import TemperatureChart from '@/components/Charts/TemperatureChart.vue';
import AirflowChart from '@/components/Charts/AirflowChart.vue';
import AllCategories from "@/components/Charts/AllCategoriesAir.vue";
import AllCategoriesTemp from "@/components/Charts/AllCategoriesTemp.vue";

export default {
  name: "Home",
  components: {
    // Register child components
    TemperatureChart,
    AirflowChart,
    AllCategories,
    AllCategoriesTemp
  },
  data() {
    return {
      chartData:{
        categories: ['指标1', '指标2', '类别3'], // x轴数据
        series: [
          {
            name: '指标1', // 系列名称
            data: [10, 20, 30] // y轴数据
          },
          {
            name: '指标2',
            data: [15, 25, 35]
          },
          // 可以添加更多系列
          {
            name: '类别3',
            data: [5, 15, 25]
          }
        ]
      },
      category_name: "",
      isday: false,
      intervalId: null,
      intervalId2: null,
      HighSection: false, // Initially false until data loads
      DataTime: '',
      suggestion: '无',
      loadingPrediction: false, // Loading state for button

      // Data properties to pass to children
      baseTempCategories: [], // For TemperatureChart base lines/bars
      baseAirCategories: [],  // For AirflowChart base lines
      currentTempData: { yAxisData: [], percentage: [], yLabel: [] }, // For TemperatureChart current line/bar
      currentAirData: { xAxisData: [], yAxisData: [] }, // For AirflowChart current line
      gridTableData: [], // For GridChart

      // Input for prediction API remains the same
      input:{
        recordTimes:[""], // Initialize empty
        clusterAlgorithm:'GMM',
        isday: false
      },

      // Default grid data structure (can be used if API fails or before load)
      defaultGrid: [
        [{checked: 0, info: {title: '单元格 1-1', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 1-2', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 1-3', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 1-4', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 1-5', name: "", status: '...'}}],
        [{checked: 0, info: {title: '单元格 2-1', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 2-2', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 2-3', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 2-4', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 2-5', name: "", status: '...'}}],
        [{checked: 0, info: {title: '单元格 3-1', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 3-2', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 3-3', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 3-4', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 3-5', name: "", status: '...'}}],
        [{checked: 0, info: {title: '单元格 4-1', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 4-2', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 4-3', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 4-4', name: "", status: '...'}}, {checked: 0, info: {title: '单元格 4-5', name: "", status: '...'}}]
      ]
    }
  },
  mounted() {
    // Initialize grid with default/empty structure
    this.gridTableData = JSON.parse(JSON.stringify(this.defaultGrid));

    // Fetch initial data
    this.getAllAirAndTemp(); // Fetch base category data first
    this.getLatestTime(); // Then get latest time and trigger prediction

    // Set up intervals (remain in parent)
    this.intervalId2 = setInterval(() => {
      console.log("Interval: Fetching latest time...");
      this.getLatestTime();
    }, 30 * 60 * 1000); // 30 minutes

    // this.intervalId = setInterval(() => {
    //   console.log("Interval: Fetching prediction...");
    //   this.getPrediction();
    // }, 10 * 1000); // 10 seconds
  },
  beforeDestroy() {
    // Clear intervals when component is destroyed
    if (this.intervalId) {
      clearInterval(this.intervalId);
      console.log("Cleared prediction interval");
    }
    if (this.intervalId2) {
      clearInterval(this.intervalId2);
      console.log("Cleared latest time interval");
    }
  },
  methods: {
    // --- Data Formatting Logic (Moved from original component) ---
    formAirlineData(air_categories) {
      const formattedCategories = [];
      if (!air_categories || air_categories.length === 0) return formattedCategories;

      air_categories.forEach(item => {
        const name = item.category_name;
        let data = [];
        if (item.air_feature) {
          const sortedFeatures = [...item.air_feature].sort((a, b) => parseInt(a.parameter_id) - parseInt(b.parameter_id));
          const idMap = { '1014': -1, '1015': -1, '1016': -1 }; // Map IDs to indices

          sortedFeatures.forEach(feature => {
            if (feature.parameter_id === '1014') idMap['1014'] = feature.value;
            if (feature.parameter_id === '1015') idMap['1015'] = feature.value;
            if (feature.parameter_id === '1016') idMap['1016'] = feature.value;
          });
          // Ensure data is in the correct order [1014, 1015, 1016]
          data = [idMap['1014'], idMap['1015'], idMap['1016']].map(val => val === -1 ? null : val); // Use null for missing values
        }
        formattedCategories.push({ name: name, data: data });
      });
      return formattedCategories;
    },

    formTempData(temp_categories) {
      const formattedCategories = [];
      if (!temp_categories || temp_categories.length === 0) return formattedCategories;

      temp_categories.forEach(item => {
        const name = item.category_name;
        let lineData = []; // For actual values
        let barData = []; // For percentages
        let yLabel = []; // Store labels from the first category processed

        if (item.temp_feature) {
          // Filter and sort by parameter_id (numeric)
          const sortedFeatures = item.temp_feature
              .filter(feature => {
                const id = parseInt(feature.parameter_id);
                return id >= 1024 && id <= 1030;
              })
              .sort((a, b) => parseInt(a.parameter_id) - parseInt(b.parameter_id));

          lineData = sortedFeatures.map(feature => feature.value);

          // Calculate percentage
          const total = lineData.reduce((acc, val) => acc + (val || 0), 0); // Handle potential nulls/undefined
          barData = total > 0 ? lineData.map(v => parseFloat(( (v || 0) / total * 100).toFixed(2))) : lineData.map(() => 0);

          // Store labels (assuming labels are consistent across categories)
          // This part might need refinement if labels differ per category
          if (formattedCategories.length === 0) { // Only get labels once
            yLabel = sortedFeatures.map(feature => feature.parameter_name || `CP${feature.parameter_id}`); // Use name or fallback
            // Assign labels to the currentTempData as well
            this.currentTempData.yLabel = yLabel.slice().reverse(); // Reverse labels for y-axis display
          }
        }

        formattedCategories.push({
          name: name,
          lineData: lineData, // Keep original order here
          barData: barData   // Keep original order here
        });
      });
      return formattedCategories;
    },

    // --- API Call Methods ---
    getAllAirAndTemp() {
      console.log("Fetching all air and temp categories...");
      this.$axios.get(this.$httpUrlVisualization + '/getAllAirAndTemp').then(res => {
        if (res.data.code === 200 && res.data.data) {
          console.log("Base categories received:", res.data.data);
          this.baseAirCategories = this.formAirlineData(res.data.data.air_categories);
          this.baseTempCategories = this.formTempData(res.data.data.temp_categories);
          // Data is now ready, allow content to show
          this.HighSection = true;
        } else {
          this.$message.warning(res.data.msg || '获取基础类别数据失败');
          this.HighSection = true; // Show section even on error, charts will be empty/default
        }
      }).catch(error => {
        console.error("Error fetching base categories:", error);
        this.$message.error('网络错误，无法获取基础类别数据');
        this.HighSection = true; // Show section even on error
      });
    },

    getLatestTime(){
      console.log("Fetching latest time...");
      this.$axios.get(this.$httpUrlVisualization + '/getLatestTimeHour').then(res => {
        if(res.data.code === 200 && res.data.data && res.data.data.latestTime){
          console.log("Latest time received:", res.data.data.latestTime);
          this.DataTime = res.data.data.latestTime;
          sessionStorage.setItem('latestTime_hour', this.DataTime);
          // Trigger prediction with the new time
          // this.getPrediction();
        }else {
          this.$message.warning(res.data.msg || '获取最新时间失败');
          // Optionally trigger prediction with existing DataTime or handle error
          if (!this.DataTime) {
            // Maybe set a default time or show error
            console.warn("No latest time available and no previous time set.");
          } else {
            // this.getPrediction(); // Try with existing time if available
          }
        }
      }).catch(error => {
        console.error("Error fetching latest time:", error);
        this.$message.error('网络错误，无法获取最新时间');
      });
    },

    getPrediction(){
      if (!this.DataTime) {
        this.$message.warning('请先选择或获取一个有效的日期时间');
        return;
      }
      if (this.loadingPrediction) return; // Prevent concurrent calls

      this.loadingPrediction = true;
      this.input.recordTimes = [this.DataTime];
      this.input.isday = this.isday;
      console.log("Requesting prediction with input:", JSON.stringify(this.input));

      this.$axios.post(this.$Python + '/predict',this.input).then(res => {
        console.log("Prediction response received:", res.data);
        if(res.data.code === 200 && res.data.data){
          const predictionData = res.data.data;
          const chartData = predictionData.chart_data;

          // Update data for Temperature Chart
          if (chartData && chartData.temp) {
            // Reverse data for correct chart display (bottom to top)
            this.currentTempData = {
              yAxisData: chartData.temp.yAxisdata?.slice().reverse() || [],
              percentage: chartData.temp.percentage?.slice().reverse() || [],
              yLabel: chartData.temp.xAxisdata?.slice().reverse() || [] // Assuming temp.xAxisdata holds Y-axis labels
            };
          } else {
            this.currentTempData = { yAxisData: [], percentage: [], yLabel: this.currentTempData.yLabel || [] }; // Clear data but keep labels if available
            console.warn("Prediction response missing temperature chart data.");
          }


          // Update data for Airflow Chart
          if (chartData && chartData.air) {
            this.currentAirData = {
              xAxisData: chartData.air.xAxisdata || [],
              yAxisData: chartData.air.yAxisdata || []
            };
          } else {
            this.currentAirData = { xAxisData: this.currentAirData.xAxisData || [], yAxisData: [] }; // Clear data but keep labels if available
            console.warn("Prediction response missing airflow chart data.");
          }

          // Update data for Grid Chart
          this.gridTableData = predictionData.optim_grid && predictionData.optim_grid.length > 0
              ? predictionData.optim_grid
              : JSON.parse(JSON.stringify(this.defaultGrid)); // Use default if empty/missing


          // Update suggestion and category name
          this.suggestion = predictionData.suggestion || '无';
          this.category_name = predictionData.predicted_category?.category_name || '未知';

          // Ensure HighSection is true after first successful prediction
          this.HighSection = true;

        } else {
          this.$message.warning(res.data.msg || '查询预测数据失败');
          // Reset data on failure? Or keep previous state?
          // Example: Reset current data but keep base and grid structure
          this.currentTempData = { yAxisData: [], percentage: [], yLabel: this.currentTempData.yLabel || [] };
          this.currentAirData = { xAxisData: this.currentAirData.xAxisData || [], yAxisData: [] };
          // Optionally reset grid or keep last known state
          // this.gridTableData = JSON.parse(JSON.stringify(this.defaultGrid));
          this.suggestion = '查询失败';
          this.category_name = '---';
        }
      }).catch(error => {
        console.error("Error during prediction request:", error);
        this.$message.error('网络错误，无法获取预测数据');
        // Reset states on network error
        this.currentTempData = { yAxisData: [], percentage: [], yLabel: this.currentTempData.yLabel || [] };
        this.currentAirData = { xAxisData: this.currentAirData.xAxisData || [], yAxisData: [] };
        // this.gridTableData = JSON.parse(JSON.stringify(this.defaultGrid));
        this.suggestion = '查询失败';
        this.category_name = '---';
      }).finally(() => {
        this.loadingPrediction = false; // Always stop loading
      });
    },

    // adjustTimeToEndOfMinute method remains if needed, but doesn't seem used currently
    adjustTimeToEndOfMinute(dateStr) {
      // ... (implementation is correct)
    },
  },
}
</script>

<style scoped>
.home {
  display: flex;
  flex-direction: column;
  height: 90vh;
  max-height: 95vh;
  box-sizing: border-box;
  background-color: #f4f6f9;
}

.content-container {
  display: flex;
  flex: 1;
  margin: 0 10px;
  gap: 10px;
  overflow: hidden;
}

.vertical-stack {
  display: flex;
  flex-direction: column;
  flex: none; /* Changed from flex:1 to none to respect width */
  min-width: 0;
  gap: 10px;
}

.horizontal-stack {
  display: flex;
  flex: none; /* Changed from flex:1 to none to respect width */
  min-width: 0;
  gap: 10px;
}
.horizontal-stack > .chart-wrapper {
  height: 100%; /* Try to force wrapper height to fill parent */
  box-sizing: border-box; /* Ensure padding doesn't add to height */
}

.chart-wrapper {
  flex: 1;
  min-height: 0;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  padding: 10px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.footPart {
  margin: 10px 10px 5px 10px;
  border-radius: 5px;
  padding: 8px 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
  background-color: #ffffff;
  flex-shrink: 0;
  font-size: 0.95em;
}

/* Responsive adjustments */
@media (max-width: 992px) {
  .content-container {
    flex-direction: column;
  }

  .vertical-stack,
  .horizontal-stack {
    width: 100% !important;
  }

  .horizontal-stack {
    flex-direction: column;
  }
}

@media (max-width: 768px) {
  .chart-wrapper {
    min-height: 300px;
  }
}
</style>
